<template>
  <user-bg>
    <a-card class="login-panel">
      <div class="title">
        <div class="item" :class="{ actived: visible }" @click="changeLogin(true)">帐号登录</div>
        <div class="split"></div>
        <div class="item" :class="{ actived: !visible }" @click="changeLogin(false)">短信登录</div>
      </div>
      <div class="content">
        <div v-show="visible" class="account-panel">
          <a-form layout="horizontal" ref="refsform" :model="form" :rules="rules">
            <a-form-item label="" name="username">
              <a-input v-model:value="form.username" placeholder="请输入帐号" allow-clear autocomplete="off" :maxlength="11">
                <template #prefix>
                  <svg-icon name="user" style="width: 12px; height: 12px"></svg-icon>
                </template>
              </a-input>
            </a-form-item>
            <a-form-item label="" name="password">
              <a-input v-model:value="form.password" type="password" placeholder="请输入密码" allow-clear autocomplete="off" :maxlength="50">
                <template #prefix>
                  <svg-icon name="pwd" style="width: 12px; height: 12px"></svg-icon>
                </template>
              </a-input>
            </a-form-item>
          </a-form>
          <div class="forget" @click="toForget">忘记密码？</div>
        </div>
        <div v-show="!visible" class="tell-panel">
          <a-form layout="horizontal" ref="refstform" :model="tform" :rules="trules">
            <a-form-item label="" name="username">
              <a-input v-model:value="tform.username" placeholder="请输入手机号" allow-clear autocomplete="off" :maxlength="11">
                <template #prefix>
                  <svg-icon name="tell" style="width: 12px; height: 12px"></svg-icon>
                </template>
              </a-input>
            </a-form-item>
            <a-form-item label="" name="validcode">
              <a-input v-model:value="tform.validcode" placeholder="请输入图形验证码" allow-clear autocomplete="off" :maxlength="50">
                <template #prefix>
                  <svg-icon name="validcode" style="width: 12px; height: 12px"></svg-icon>
                </template>
                <template #addonAfter>
                  <valid-code ref="refsValidCode" v-model:value="validCode" />
                </template>
              </a-input>
            </a-form-item>
            <a-form-item label="" name="verificationCode">
              <a-input-search v-model:value="tform.verificationCode" placeholder="请输入短信验证码" allow-clear autocomplete="off" :maxlength="8" enter-button="获取验证码" @search="onSearch">
                <template #prefix>
                  <svg-icon name="sms" style="width: 12px; height: 12px"></svg-icon>
                </template>
              </a-input-search>
            </a-form-item>
          </a-form>
        </div>
        <a-button type="primary" :block="true" @click="authLogin">登录</a-button>
        <div class="register-panel">新用户，<span class="register" @click="toRegister">直接注册></span></div>
      </div>
    </a-card>
  </user-bg>
</template>

<script setup name="login">
import { ref, reactive, onMounted } from 'vue'
import { notification, message } from 'ant-design-vue'
import ValidCode from '@/components/Bussiness/ValidCode.vue'
import UserBg from '@/components/Bussiness/UserBg.vue'
import { ACCESS_TOKEN, HOME_PAGE_PATH } from '@/mutation-type'
import { webStorage } from '@/utils/webStorage'
import { useUserStore } from '@/store/user'
import router from '@/router'
import { pwdLogin, sendLoginSms } from '@/api/authorize'

const visible = ref(true)
const refsform = ref(null)
const refstform = ref(null)

const form = reactive({ username: 'djcms_admin', password: 'Djcms@123' })
const rules = reactive({
  username: [{ required: true, message: '请输入帐号', type: 'string', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', type: 'string', trigger: 'blur' }],
})

const validCode = ref('')
const tform = reactive({})
let validateValidCode = async (_rule, value) => {
  if (!value) {
    return Promise.reject('请输入图形验证码')
  } else {
    if (validCode.value !== value) {
      return Promise.reject('请输入正确的图形验证码')
    }
    return Promise.resolve()
  }
}
const trules = reactive({
  username: [
    { required: true, message: '请输入手机号', type: 'string', trigger: 'blur' },
    { pattern: /^1[3-9][0-9]{9}$/, message: '请输入正确的手机号' },
  ],
  validcode: [{ required: true, validator: validateValidCode, trigger: 'blur' }],
  verificationCode: [{ required: true, message: '请输入短信验证码', type: 'string', trigger: 'blur' }],
})

const onSearch = async () => {
  await sendLoginSms(tform.username)
}

const changeLogin = (status) => {
  visible.value = status
}

const toForget = () => {
  router.push(`/user/forget`)
}

const toRegister = () => {
  router.push(`/user/register`)
}

const authLogin = async () => {
  // 帐号登录
  if (visible.value) {
    await refsform.value.validate()

    const { success, msg, data } = await pwdLogin({ userData: JSON.stringify(form) })
    if (success) {
      // 清除回车事件
      document.onkeydown = null

      let user = useUserStore()
      // let userInfo = { token: `SESSION=${data.token}`, remember: { ...data.userinfo } }
      let userInfo = { token: data.token, remember: { ...data.userinfo } }
      user.setUser(userInfo)
      webStorage.ls.set(ACCESS_TOKEN, userInfo, 2 * 24 * 60 * 60 * 1000)
      // go Home
      router.push(HOME_PAGE_PATH)
    } else {
      notification.error({ message: '系统提示', description: msg, duration: 4 })
      // message.error(msg)
    }
  } else {
    await refstform.value.validate()

    const params = { ...tform, loginType: 1 }
    delete params.validcode
    const { success, msg, data } = await pwdLogin({ userData: JSON.stringify(params) })
    if (success) {
      // 清除回车事件
      document.onkeydown = null

      let user = useUserStore()
      let userInfo = { token: data.token, remember: { ...data.userinfo } }
      user.setUser(userInfo)
      webStorage.ls.set(ACCESS_TOKEN, userInfo, 2 * 24 * 60 * 60 * 1000)
      // go Home
      router.push(HOME_PAGE_PATH)
    } else {
      notification.error({ message: '系统提示', description: msg, duration: 4 })
      // message.error(msg)
    }
  }
}

onMounted(() => {
  document.onkeydown = () => {
    //!this.clickState是防止用户重复点击回车
    if (window.event.keyCode === 13) authLogin()
  }
})
</script>

<style lang="less" scoped>
@import url('@/assets/style/authorize.less');
.login-panel {
  width: 340px;
  // width: 460px;
  // height: 460px;
  .title {
    display: flex;
    justify-content: center;

    font-size: 20px;
    font-family:
      PingFangSC-Regular,
      PingFang SC;
    // font-weight: 400;
    color: #222222;
    line-height: 30px;
    .item {
      flex-grow: 1;
      text-align: center;
      cursor: pointer;
    }
    .actived {
      color: #e1251b;
    }
    .split {
      align-self: center;
      height: 16px;
      width: 1px;
      background-color: silver;
    }
  }
  .content {
    display: flex;
    flex-flow: column nowrap;
    // height: 380px;
    padding: 20px 0;

    font-size: 14px;
    font-family:
      PingFangSC-Regular,
      PingFang SC;
    font-weight: 400;
    color: #222222;
    line-height: 22px;
    .account-panel {
      .forget {
        text-align: right;
        padding-bottom: 10px;
        cursor: pointer;
      }
    }
    .tell-panel {
    }

    .register-panel {
      padding-top: 10px;
      text-align: right;
      .register {
        color: #e1251b;
        cursor: pointer;
      }
    }
  }
}
</style>
